﻿#include "toolwidget.h"
#include "ui_toolwidget.h"

ToolWidget::ToolWidget(Tree* treedata, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ToolWidget)
{
    ui->setupUi(this);
    init();
    initConnections();
    tree = treedata;
}

ToolWidget::~ToolWidget()
{
    delete ui;
}

//初始化ui控件和一些参数
void ToolWidget::init(){
    QPalette palette = this->palette();
    palette.setBrush(QPalette::Window, QBrush(QColor(240, 240, 240), Qt::SolidPattern));
    this->setAutoFillBackground(true);
    this->setPalette(palette);
    ui->KeyDate->hide();
    ui->Return->hide();
    ui->KeyEdu->hide();
    isAddingNew = false;
    isAddingChild = false;
    isAddingAncestry = false;

    //初始化表格
    ui->tableKW->setSelectionBehavior(QAbstractItemView::SelectRows);//选择整行
    ui->tableKW->setGridStyle(Qt::DashLine);//设置格子线
    ui->tableKW->setEditTriggers(QAbstractItemView::NoEditTriggers);//禁止编辑
    ui->tableKW->horizontalHeader()->setStretchLastSection(true);//列填充
    ui->tableKW->verticalHeader()->setDefaultSectionSize(20);//设置默认行高
    ui->tableKW->setSelectionMode(QAbstractItemView::SingleSelection);//设置单行选择
    ui->tableKW->setColumnCount(3);
    ui->tableKW->hide();

    ui->tableRL->setSelectionBehavior(QAbstractItemView::SelectRows);//选择整行
    ui->tableRL->setGridStyle(Qt::DashLine);//设置格子线
    ui->tableRL->setEditTriggers(QAbstractItemView::NoEditTriggers);//禁止编辑
    ui->tableRL->horizontalHeader()->setStretchLastSection(true);//列填充
    ui->tableRL->verticalHeader()->setDefaultSectionSize(20);//设置默认行高
    ui->tableRL->setSelectionMode(QAbstractItemView::SingleSelection);//设置单选择
    ui->tableRL->setColumnCount(2);
    ui->tableRL->hide();
}

//初始化Connect
void ToolWidget::initConnections(){

    //关闭按钮
    connect(ui->ExitDetail, &QPushButton::clicked, this, &ToolWidget::closeToolArea);
    connect(ui->ExitStat, &QPushButton::clicked, this, &ToolWidget::closeToolArea);
    connect(ui->ExitSearch, &QPushButton::clicked, [this]{
        clearKWPage(), emit closeToolArea();
    });
    connect(ui->ExitRelation, &QPushButton::clicked, [this]{
        clearRSPage(), emit closeToolArea();
    });

    //在搜索关键词，根据搜索信息的种类，改变输入框
    connect(ui->Kind, &QComboBox::currentTextChanged, this, &ToolWidget::keyWordKindChanged);

    //详情页保存按钮按下时
    connect(ui->Save, &QPushButton::clicked, this, &ToolWidget::saveButtonClicked);

    connect(ui->SearchKW, &QPushButton::clicked, this, &ToolWidget::keyWordSearch);

    connect(ui->SearchRL, &QPushButton::clicked, this, &ToolWidget::reletiveSearch);

    //在搜索结果和亲戚查询的结果的表格的项目被双击时，跳转到相应详情页面
    connect(ui->tableKW, &QTableWidget::itemDoubleClicked, [this](QTableWidgetItem* temp){
        emit fromKWSearchToDetail(ui->tableKW->item(temp->row(),0)->text().toInt());
        prevPage = 0;
    });
    connect(ui->tableRL, &QTableWidget::itemDoubleClicked, [this](QTableWidgetItem* temp){
        emit fromKWSearchToDetail(ui->tableRL->item(temp->row(),0)->text().toInt());
        prevPage = 1;
    });

    //返回按钮按下
    connect(ui->Return, &QPushButton::clicked, [this]{
        emit retrunToPrevPage(prevPage);
    });

    //删除按钮按下
    connect(ui->Delete, &QPushButton::clicked, [this]{
        emit deleteValue(processID);
        emit closeToolArea();
    });
}

//返回当前工具页面的index
int ToolWidget::currentIndex(){
    return ui->ToolArea->currentIndex();
}

//设置工具页面
void ToolWidget::setCurrentIndex(int index){
    ui->ToolArea->setCurrentIndex(index);
}

//更新主题
void ToolWidget::updateTheme(QColor newTheme, QColor oldTheme){
    QString stylesheet = styleSheet();
    stylesheet.replace(oldTheme.name().remove("#"),newTheme.name().remove("#"));
    setStyleSheet(stylesheet);
}

//添加新项目
void ToolWidget::addValueToData(int fatherID, int partnerID){
    //获取文本框的各项内容//
    QString name = ui->Name->text().trimmed();
    if(name.isEmpty()){
        name = "无名氏";
    }
    QString birthplace = ui->Birthplace->text();
    QString gender = ui->Man->isChecked()? "男":"女";
    double stature = ui->Stature->value();
    QString job = ui->Job->text();
    QString edubg = ui->EduBg->currentText();
    QString birthday = ui->Birthday->date().toString(QStringView(QString("yyyy-MM-dd")));
    QString deathday = ui->Deathday->date().toString(QStringView(QString("yyyy-MM-dd")));
    QString highestjob = ui->HighestJob->text();
    QString lifetime = ui->LifeTime->toPlainText();

    QStringList list;
    list<<name<<birthplace<<gender<<QString("%1").arg(stature)<<job
       <<edubg<<birthday<<deathday<<highestjob<<lifetime;

    //调用tree的添加函数
    tree->addValue(fatherID, partnerID, list);
}

//更新项目数据
void ToolWidget::updateValueToData(int curID){

    //获取ui界面的内容
    QString name = ui->Name->text().trimmed();
    if(name.isEmpty()){
        name = "无名氏";
    }
    QString birthplace = ui->Birthplace->text();
    QString gender = ui->Man->isChecked()? "男":"女";
    double stature = ui->Stature->value();
    QString job = ui->Job->text();
    QString edubg = ui->EduBg->currentText();
    QString birthday = ui->Birthday->date().toString(QStringView(QString("yyyy-MM-dd")));
    QString deathday = ui->Deathday->date().toString(QStringView(QString("yyyy-MM-dd")));
    QString highestjob = ui->HighestJob->text();
    QString lifetime = ui->LifeTime->toPlainText();

    QStringList list;
    list<<name<<birthplace<<gender<<QString("%1").arg(stature)<<job
       <<edubg<<birthday<<deathday<<highestjob<<lifetime;

    //调用tree的数据更新函数
    tree->updateValue(curID, list);

}

//从tree获取数据
void ToolWidget::readValueFromData(){

    qDebug()<<processID;
    QStringList Data = tree->readValue(processID);

    //初始化变量名
    QString name = Data.at(0);
    QString birthplace = Data.at(1);
    QString gender = Data.at(2);
    double stature = Data.at(3).toDouble();
    QString job = Data.at(4);
    QString edubg = Data.at(5);
    QString birthday = Data.at(6);
    QString deathday = Data.at(7);
    QString highestjob = Data.at(8);
    QString lifetime = Data.at(9);

    if(tree->isFather(processID)){
        disableWomanChoice();
    }
    else if(tree->isMother(processID)){
        disableManChoice();
    }

    //显示数据
    ui->Name->setText(name);
    ui->Birthplace->setText(birthplace);
    if(gender == "男"){
        ui->Man->setChecked(true);
    }
    else{
        ui->Woman->setChecked(true);
    }
    ui->Stature->setValue(stature);
    ui->EduBg->setCurrentText(edubg);
    ui->Job->setText(job);
    ui->Birthday->setDate(QDate::fromString(birthday, "yyyy-MM-dd"));
    ui->Deathday->setDate(QDate::fromString(deathday, "yyyy-MM-dd"));
    ui->HighestJob->setText(highestjob);
    ui->LifeTime->setPlainText(lifetime);
}

//亲戚关系查询
void ToolWidget::reletiveSearch(){
    //清除原来的结果
    ui->tableRL->clear();
    ui->tableRL->show();

    //调用tree的函数，获得一个结果的ID列表
    QList<int> resultList = tree->searchRL(RLSearchID, ui->relKind->currentText());

    //如果得到的结果列表为空，退出函数
    if(resultList.isEmpty()){
        QStringList header;
        header<<"ID"<<"没有匹配的项";
        ui->tableRL->hideColumn(0);
        ui->tableRL->setRowCount(0);
        ui->tableRL->setHorizontalHeaderLabels(header);
        return;
    }
    else{
        QStringList header;
        header<<"ID"<<"查询结果";
        ui->tableRL->setHorizontalHeaderLabels(header);
    }
    ui->tableRL->hideColumn(0);

    QTableWidgetItem* tp = nullptr;
    TreeNode* data = nullptr;

    ui->tableRL->setRowCount(resultList.size());
    int row = 0;
    for(int id : resultList){
        data = tree->getValueFromID(id);
        //每一行的第一列储存ID，方便之后的详情页数据的访问
        tp = new QTableWidgetItem(QString("%1").arg(data->ID));
        ui->tableRL->setItem(row, 0, tp);
        tp = new QTableWidgetItem(QString("%1").arg(data->Name));
        ui->tableRL->setItem(row, 1, tp);
        row++;
    }

    ui->tableRL->setRowCount(resultList.size());
}

//保存按钮按下的槽函数时，处理一些判断操作
void ToolWidget::saveButtonClicked(){

    //判断出生日期和死亡日期的填写是否合法
    //如果非法，弹窗提示
    if(ui->Birthday->date().daysTo(ui->Deathday->date())<0){
        QMessageBox *info = new QMessageBox(QMessageBox::Information, "提示",
                                               "请确认出生日期和死亡日期的填写是否出错",
                                            QMessageBox::Yes, this);
        info->button(QMessageBox::Yes)->setText("确定");
        info->exec();
        return;
    }


    //判断是否为祖先
    if(isAddingAncestry){
        addValueToData(-1, -1);
        emit addedAncestry();
        isAddingAncestry = false;
        return;
    }
    //判断是否是在新建
    if(isAddingNew){
        if(isAddingChild){
            addValueToData(processID, -2);
            emit addedChild(processID);
            processID = tree->getValueFromID(processID)->SonList.last();
        }
        else{
            addValueToData(-2, processID);
            emit addedMate(processID);
            processID = tree->getValueFromID(processID)->PartnerNode->ID;
        }
        isAddingNew = false;
    }
    else{
        updateValueToData(processID);
        emit updateValue(processID);
    }
}

//搜索按钮按下时的槽函数，处理搜索结果
void ToolWidget::keyWordSearch(){
    //清除原来的结果
    ui->tableKW->clear();
    QString kind = ui->Kind->currentText();
    QString info = "";
    QStringList header;
    header<<"ID"<<"姓名"<<kind;
    ui->tableKW->setHorizontalHeaderLabels(header);
    ui->tableKW->show();

    if(kind == "出生日期" or kind == "死亡日期"){
        info = ui->KeyDate->date().toString(QStringView(QString("yyyy-MM-dd")));
    }
    else if(kind == "学历"){
        info = ui->KeyEdu->currentText();
    }
    else{
        info = ui->KeyWord->text();
    };

    //调用tree的关键字搜索函数，获得结果的列表
    QList<int> resultList = tree->searchKW(info, kind);

    //如果列表为空，退出函数
    if(resultList.isEmpty()){
        QStringList header;
        header<<"没有匹配的项";
        ui->tableKW->setHorizontalHeaderLabels(header);
        ui->tableKW->showColumn(0);
        ui->tableKW->hideColumn(1);
        ui->tableKW->hideColumn(2);
        return;
    }
    else{
        QStringList header;
        header<<"ID"<<"姓名"<<kind;
        ui->tableKW->setHorizontalHeaderLabels(header);
        ui->tableKW->hideColumn(0);
        ui->tableKW->showColumn(1);
        ui->tableKW->showColumn(2);
    }

    ui->tableKW->setRowCount(resultList.size());
    QTableWidgetItem* tp;
    TreeNode* data;

    int row = 0;
    for(int id : resultList){
        data = tree->getValueFromID(id);

        //每一行的第一列储存ID，方便之后的详情页数据的访问
        tp = new QTableWidgetItem(QString("%1").arg(data->ID));
        ui->tableKW->setItem(row, 0, tp);

        tp = new QTableWidgetItem(QString("%1").arg(data->Name));
        ui->tableKW->setItem(row, 1, tp);

        if(kind == "出生地"){
            tp = new QTableWidgetItem(QString("%1").arg(data->Birthplace));
            ui->tableKW->setItem(row, 2, tp);
        }
        else if(kind == "出生日期"){
            tp = new QTableWidgetItem(QString("%1").arg(data->Birthday));
            ui->tableKW->setItem(row, 2, tp);
        }
        else if(kind == "死亡日期"){
            tp = new QTableWidgetItem(QString("%1").arg(data->Deathday));
            ui->tableKW->setItem(row, 2, tp);
        }

        else if(kind == "学历"){
            tp = new QTableWidgetItem(QString("%1").arg(data->EduBg));
            ui->tableKW->setItem(row, 2, tp);
        }
        else if(kind == "职业"){
            tp = new QTableWidgetItem(QString("%1").arg(data->Job));
            ui->tableKW->setItem(row, 2, tp);
        }

        else if(kind == "最高职业"){
            tp = new QTableWidgetItem(QString("%1").arg(data->HighestJob));
            ui->tableKW->setItem(row, 2, tp);
        }
        else if(kind == "生平事迹"){
            tp = new QTableWidgetItem(QString("%1").arg(data->LifeTime));
            ui->tableKW->setItem(row, 2, tp);
        }
        row++;
    }

    ui->tableKW->setRowCount(resultList.size());

    if(kind!="姓名"){
        ui->tableKW->showColumn(2);
    }
    else{
        ui->tableKW->hideColumn(2);
    }


}

//搜索页面，搜索类型更改时，更改输入类型
void ToolWidget::keyWordKindChanged(QString text){
    if(text == "出生日期" or text == "死亡日期"){
        ui->KeyDate->show();
        ui->KeyWord->hide();
        ui->KeyEdu->hide();
    }
    else if(text == "学历"){
        ui->KeyDate->hide();
        ui->KeyWord->hide();
        ui->KeyEdu->show();
    }
    else{
        ui->KeyDate->hide();
        ui->KeyWord->show();
        ui->KeyEdu->hide();
    }
}

//刷新关系查询页面
void ToolWidget::clearRSPage(){
    ui->relKind->setCurrentIndex(0);
    ui->tableRL->clear();
    ui->tableRL->hide();
}

//刷新关键字搜索页面
void ToolWidget::clearKWPage(){
    ui->Kind->setCurrentIndex(0);
    ui->KeyWord->clear();
    ui->KeyDate->clear();
    ui->tableKW->clear();
    ui->tableKW->hide();
}

//刷新详情页面
void ToolWidget::clearDTPage(){
    ui->Name->clear();
    ui->Birthplace->clear();
    ui->Man->setChecked(true);
    ui->Stature->setValue(0);
    ui->EduBg->setCurrentIndex(0);
    ui->Job->clear();
    ui->Birthday->setDate(QDate::fromString("2000-1-1", "yyyy-MM-dd"));
    ui->Deathday->setDate(QDate::fromString("2000-1-1", "yyyy-MM-dd"));
    ui->HighestJob->clear();
    ui->LifeTime->clear();
    ui->Return->hide();
    ui->spacingR->show();
    ui->Man->setEnabled(true);
    ui->Woman->setEnabled(true);
    ui->Delete->setEnabled(true);
}

//关闭女性选项
void ToolWidget::disableWomanChoice(){
    ui->Man->setChecked(true);
    ui->Woman->setDisabled(true);
}

//关闭男性选项
void ToolWidget::disableManChoice(){
    ui->Woman->setChecked(true);
    ui->Man->setDisabled(true);
}

//设置返回按钮的显示
void ToolWidget::showReturnButton(){
    ui->Return->show();
    ui->spacingR->hide();
}

//刷新统计数据的页面
void ToolWidget::refreshState(){
    ui->AvgEdu->setText(tree->getAvgEdu());
    ui->AvgSta->setText(QString::number(tree->getAvgStature(), 'f', 1)+"厘米");
    ui->AvgPer->setText(QString("%1").arg(tree->getAvgPerson())+"人");
    ui->AvgLife->setText(QString::number(tree->getAvgLife(), 'f', 1)+"岁");
    int manp = tree->getProportion();
    ui->progressBar->setValue(manp);
    ui->MW->setText(QString("男性占比%1%").arg(manp));
    ui->Num->setText(QString("%1人").arg(tree->getALLID().size()));
}

//在新建祖先时关闭删除按钮
void ToolWidget::disableDel(){
    ui->Delete->setDisabled(true);
}

//设置搜索的ID
void ToolWidget::setRLSearchID(int id){
    RLSearchID = id;
}

